﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.OleDb;

namespace DAO
{
    class DataAccess
    {
        //thuoc tin
        protected static String m_connectionString = 
            "Provider = Microsoft.Jet.OleDb.4.0; Data Source = ./Database_BongDa.mdb";
        protected static OleDbConnection connection;
        //phuong thuc
        //ham tao

        //ket noi
        public static void connect()
        {
            try
            {
                connection = new OleDbConnection(connectionString);
                connection.Open();
            }
            catch (Exception ex)
            {
                // MessageBox.Show("Không thể kết nối được với Server\n" + ex.Message, "Lỗi chương trình");
                //Application.Exit();
            }
        }
        //tat ket noi
        public static void disConnect()
        {
            try
            {
                connection.Close();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        //lay du lieu ra tu table
        public static DataTable executeQuery(string sqlString)
        {
            connect();
            DataTable dt = new DataTable();
            OleDbCommand cm = connection.CreateCommand();
            cm.CommandText = sqlString;
            OleDbDataAdapter da = new OleDbDataAdapter();
            da.SelectCommand = cm;
            da.Fill(dt);
            disConnect();
            return dt;
        }
        //dung cho cac thao tac insert, update, delete
        public static void executeNonQuery(string sqlString)
        {
            connect();
            OleDbCommand command = connection.CreateCommand();
            command.CommandText = sqlString;
            command.ExecuteNonQuery();
            disConnect();
        }
        //dung cho cac thao tac insert, update, khi co hinh anh
        public static void executeNonQuery(OleDbCommand command)
        {
            connect();
            command.Connection = connection;
            command.ExecuteNonQuery();
            disConnect();
        }
        //lay 1 gia tri du lieu ra
        public static object executeScalar(string sqlString)
        {
            connect();
            OleDbCommand command = connection.CreateCommand();
            command = new OleDbCommand(sqlString, connection);
            object o = command.ExecuteScalar();
            disConnect();
            return o;
        }

        public static string connectionString
        {
            get
            {
                return m_connectionString;
            }
            set
            {
                m_connectionString = value;
            }
        }
    }
}
